package
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.media.ID3Info;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.net.URLRequest;

	public class MusicSound extends EventDispatcher
	{
		private		var	_url:String = null;
		private		var _sound:Sound = null;
		private		var _soundChan:SoundChannel = null;
		private		var _pos:int = 0;
		private		var _isPlay:Boolean = false;
		
		public function MusicSound(url:String)
		{
			this._url = url;
			
			var urlReq:URLRequest = new URLRequest(this._url);
			
			this._sound = new Sound(urlReq, new SoundLoaderContext(5000, false));
			this._sound.addEventListener(Event.ID3, onID3);
		}
		
		public	function	play():Boolean{
			this._soundChan = this._sound.play(this._pos);
			if (this._soundChan == null)
				return false;
			this._isPlay = true;
			this._soundChan.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			return true;
		}
		
		public	function	pause():void{
			if (this._isPlay == false)
				return;
			
			this._pos = this._soundChan.position;
			this._soundChan.stop();
			this._isPlay = false;
		}
		
		public	function	stop():void{
			if (this._isPlay == false)
				return;
			
			this._soundChan.stop();
			this._pos = 0;
			this._isPlay = false;
		}
		
		public	function	getLoadPercent():Number{
			return this._sound.bytesLoaded/this._sound.bytesTotal;
		}
		
		public	function	getPlayPercent():Number{
			var totalLen:Number = 0;
			if (this._sound != null){
				totalLen = this._sound.length /this.getLoadPercent();
			}
			else{
				return 0;
			}
			
			if (this._isPlay == false){
				return this._pos / totalLen;
			}

			return this._soundChan.position / totalLen;
		}
		
		public	function	onID3(evt:Event):void{
			this.dispatchEvent(evt);
		}
		
		public	function	get id3():ID3Info{
			//return this._sound.id3;
			return null;
		}
		
		public	function	onSoundComplete(evt:Event):void{
			this.dispatchEvent(evt);
		}
		
		public	function	getPlayPos():int{
			if (this._soundChan != null){
				return this._soundChan.position;
			}
			else{
				return 0;
			}
		}
		
		public	function	getSoundLength():int{
			var totalLen:Number = 0;
			if (this._sound != null){
				totalLen = this._sound.length /this.getLoadPercent();
			}
			
			return totalLen;
		}
	}
}